package com.base.commonlib.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.R;
import com.base.commonlib.bean.TaskInfo;


/**
 * Created by weikailiang on 2019/11/7.
 */

public class DownLoadUtils {
    private Context mContext;
    private boolean isPdf;
    public DownLoadUtils(Context context, TaskInfo info, boolean isPdf){
        this.mContext = context;
        this.info = info;
        this.isPdf = isPdf;
    }
    private DownloadRunnable runnable;//下载任务
    private TaskInfo info = null;//任务信息
    //用于更新进度的Handler
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //使用Handler制造一个200毫秒为周期的循环
            handler.sendEmptyMessageDelayed(1, 200);

            if (info.isError()){
                if (mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                ToastUtil.show("下载失败");
                handler.removeCallbacksAndMessages(null);
            }
            if (info.getContentLen()==0){
                //为获取到文件长度
                if (info.isCommpany()){
                    bar.setProgress(100);
                    text.setText(100 + "%");
                    handler.removeCallbacksAndMessages(null);
                    if (mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    checkIsAndroidO();
                }else {
                    text.setText("正在下载中，请等待");
                }
            }else {
                //计算下载进度
                int l = (int) ((float) info.getCompletedLen() / (float) info.getContentLen() * 100);
                //设置进度条进度
                bar.setProgress(l);
                text.setText(l + "%");
                if (l >= 100) {//当进度>=100时，取消Handler循环
                    handler.removeCallbacksAndMessages(null);
                    if (mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    checkIsAndroidO();

                }
            }
            return true;
        }
    });
    Dialog mDialog;
    ProgressBar bar;
    TextView text;
    ImageView mPause;
    boolean b;
    public void showDownDialog(){
        mDialog = new Dialog(mContext);
        View v = LayoutInflater.from(mContext).inflate(R.layout.item_dialog,null);
        bar = v.findViewById(R.id.progress_bar);
        mPause = v.findViewById(R.id.pause);
        text = v.findViewById(R.id.num);
        mDialog.setContentView(v);
        mDialog.setCancelable(false);
        mDialog.setTitle("提示");
        mDialog.show();
        mPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!b){
                    mPause.setImageResource(R.drawable.ic_start);
                    stop(null);
                }else {
                    mPause.setImageResource(R.drawable.ic_pause);
                    startApk(null);
                }
                b = !b;
            }
        });
        startApk(null);
    }
    /**
     * 开始下载按钮监听
     * @param view
     */
    public void startApk(View view) {
        //创建下载任务
        runnable = new DownloadRunnable(info);
        //开始下载任务
        new Thread(runnable).start();
        //开始Handler循环
        handler.sendEmptyMessageDelayed(1, 200);
    }
    /**
     * 停止下载按钮监听
     * @param view
     */
    public void stop(View view) {
        //调用DownloadRunnable中的stop方法，停止下载
        runnable.stop();
        runnable = null;//强迫症，不用的对象手动置空
    }
    private void checkIsAndroidO(){
        if (isPdf){
            ARouter.getInstance().build("/sweb/common")
                    .withInt("key",6)
                    .withString("name",info.getName())
                    .withString("title","文件")
                    .withString("url",info.getPath()+info.getName())
                    .navigation();
        }else {
            MultiFileUtil.showPdf(mContext, info.getPath()+info.getName());
        }
    }
    public void onDestory(){
        if (handler != null){
            handler.removeCallbacksAndMessages(null);
        }

    }
}
